# ============================================
# AstrBot 一键部署脚本 (Windows)
# 功能：自动创建目录、下载配置文件并启动容器
# ============================================

# 设置错误时停止执行
$ErrorActionPreference = "Stop"

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

Write-ColorOutput "=====================================" "Green"
Write-ColorOutput "   AstrBot 一键部署脚本 (Windows)" "Green"
Write-ColorOutput "=====================================" "Green"

# 检查 Docker 是否安装
Write-ColorOutput "[1/5] 检查依赖工具..." "Yellow"
try {
    $dockerVersion = docker --version
    Write-ColorOutput "✓ Docker 已安装: $dockerVersion" "Green"
} catch {
    Write-ColorOutput "错误：未找到 docker 命令，请先安装 Docker Desktop" "Red"
    exit 1
}

# 创建目录
Write-ColorOutput "[2/5] 创建 astrbot 目录..." "Yellow"
$targetDir = "astrbot"

if (Test-Path $targetDir) {
    Write-ColorOutput "目录已存在，将使用现有目录" "Yellow"
} else {
    New-Item -ItemType Directory -Path $targetDir | Out-Null
}

Write-ColorOutput "✓ 目录创建完成" "Green"

# 进入目录
Set-Location $targetDir
Write-ColorOutput "当前工作目录: $(Get-Location)" "Yellow"

# 下载配置文件
Write-ColorOutput "[3/5] 下载 astrbot.yml 配置文件..." "Yellow"
$downloadUrl = "https://raw.githubusercontent.com/NapNeko/NapCat-Docker/main/compose/astrbot.yml"
$outputFile = "astrbot.yml"

try {
    # 使用 Invoke-WebRequest 下载文件
    Invoke-WebRequest -Uri $downloadUrl -OutFile $outputFile -UseBasicParsing
    
    if (Test-Path $outputFile) {
        Write-ColorOutput "✓ 配置文件下载完成" "Green"
    } else {
        throw "文件下载后未找到"
    }
} catch {
    Write-ColorOutput "错误：配置文件下载失败 - $_" "Red"
    Set-Location ..
    exit 1
}

# 检查 Docker 服务状态
Write-ColorOutput "[4/5] 检查 Docker 服务状态..." "Yellow"
try {
    docker ps | Out-Null
    Write-ColorOutput "✓ Docker 服务运行正常" "Green"
} catch {
    Write-ColorOutput "警告：Docker 服务可能未运行，请确保 Docker Desktop 已启动" "Yellow"
}

# 启动容器
Write-ColorOutput "[5/5] 启动 AstrBot 容器..." "Yellow"
try {
    docker compose -f astrbot.yml up -d
    
    Write-ColorOutput "=====================================" "Green"
    Write-ColorOutput "   AstrBot 部署成功！" "Green"
    Write-ColorOutput "=====================================" "Green"
    Write-ColorOutput "" "White"
    
    # 等待容器启动并获取 Token
    Write-ColorOutput "正在等待容器启动..." "Yellow"
    Start-Sleep -Seconds 3
    
    # 获取本机 IP 地址
    $localIP = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -notlike "127.*" -and $_.IPAddress -notlike "169.*" } | Select-Object -First 1).IPAddress
    if (-not $localIP) {
        $localIP = "localhost"
    }
    
    Write-ColorOutput "访问地址：" "Green"
    Write-ColorOutput "  - AstrBot WebUI:  http://${localIP}:6185" "Cyan"
    Write-ColorOutput "  - NapCat WebUI:   http://${localIP}:6099" "Cyan"
    Write-ColorOutput "" "White"
    
    # 尝试提取 NapCat WebUi Token
    Write-ColorOutput "正在获取 NapCat WebUi Token..." "Yellow"
    Start-Sleep -Seconds 3
    
    try {
        $ErrorActionPreference = "Continue"
        $napcat_logs = docker logs napcat 2>&1 | Out-String
        $ErrorActionPreference = "Stop"
        
        # 使用更宽松的正则，匹配带时间戳的日志格式
        if ($napcat_logs -match "Token:\s*([a-f0-9]+)") {
            $token = $matches[1]
            Write-ColorOutput "  - NapCat Token:   $token" "Green"
        } else {
            Write-ColorOutput "  - NapCat Token:   (未获取到，请稍后查看日志)" "Yellow"
        }
    } catch {
        Write-ColorOutput "  - NapCat Token:   (容器可能还在启动中)" "Yellow"
    }
    
    Write-ColorOutput "" "White"
    Write-ColorOutput "常用命令：" "Yellow"
    Write-ColorOutput "  - 查看容器状态: docker compose -f astrbot.yml ps" "Cyan"
    Write-ColorOutput "  - 查看 AstrBot 日志: docker logs -f astrbot" "Cyan"
    Write-ColorOutput "  - 查看 NapCat 日志: docker logs -f napcat" "Cyan"
    Write-ColorOutput "  - 停止服务: docker compose -f astrbot.yml down" "Cyan"
    Write-ColorOutput "  - 重启服务: docker compose -f astrbot.yml restart" "Cyan"
    
} catch {
    Write-ColorOutput "错误：容器启动失败 - $_" "Red"
    Write-ColorOutput "请检查 Docker Desktop 是否正在运行" "Yellow"
    Set-Location ..
    exit 1
}

# 返回上级目录
Set-Location ..

Write-ColorOutput "" "White"
Write-ColorOutput "提示：请执行以下命令查看 NapCat 日志并扫码登录 QQ" "Yellow"
Write-ColorOutput "      docker logs -f napcat" "Cyan"